<template>
  <div>
    <div>
      <el-button @click="get">获取内容</el-button>
      <el-button @click="insert">插入内容</el-button>
      <el-button @click="set">覆盖全部内容</el-button>
    </div>
    <!-- markdown容器 -->
    <div id="markdown-container"></div>
  </div>
</template>

<script setup lang="ts">
import Vditor from "vditor";
import "../../../node_modules/vditor/src/assets/less/index.less";
import { Storage } from "@/utils/storage";
import { ACCESS_TOKEN_KEY } from "@/constants/cache-keys";

const vditor = ref<Vditor>();

onMounted(() => {
  vditor.value = new Vditor("markdown-container", {
    // 工具栏显示
    // toolbar: ['emoji', 'br', 'bold', '|', 'line']
    // 是否隐藏、固定工具栏
    toolbarConfig: { hide: false, pin: true },
    // 初始化是否展现大纲
    outline: {
      enable: true,
      // 大纲所在位置
      position: "right",
    },
    // 默认模式
    mode: "wysiwyg",
    // 是否使用本地存储
    cache: {
      enable: true,
      // 缓存后的回调
      after(html: string) {
        console.log(html);
      },
    },
    // 上传文件
    upload: {
      url: "http://127.0.0.1:4000/api/admin/upload",
      fieldName: "avatar",
      // 限制上传文件必须为图片
      accept: "image/*",
      success(editor: HTMLPreElement, msg: string) {
        let result = JSON.parse(msg);
        let photoUrl = result.data.server_url + result.data.path;
        vditor.value?.insertValue(`![长江二桥](${photoUrl})`);
      },
      headers: {
        // JWT token
        Authorization: Storage.get(ACCESS_TOKEN_KEY),
      },
    },
  });
});

// 获取内容
const get = () => {
  // console.log(vditor.value?.getValue());
  console.log(vditor.value?.getHTML());
};

// 在光标处插入内容
const insert = () => {
  vditor.value?.insertValue("# 长江二桥");
};

// 覆盖全部内容
const set = () => {
  vditor.value?.setValue("# 长江二桥");
};
</script>

<style scoped></style>
